<template>
  <client-only>
    <Editor :style="$attrs.style" :api-key="apiKey" :init="initConfig" @init="onInit" v-model="htmlContent"></Editor>
  </client-only>
</template>

<script setup lang="ts">
import Editor from '@tinymce/tinymce-vue'
import type { Editor as EditorType } from 'tinymce'

/**
 * tinymce 没有导出这个类型，copy过来的
 */
type FilePickerCallback = (
  callback: (value: string, meta?: Record<string, any>) => void,
  value: string,
  meta: Record<string, any>
) => void

const emits = defineEmits(['init', 'update:modelValue'])

const htmlContent = ref('')

const apiKey = import.meta.env.VITE_TINYMCE_API_KEY

const file_picker_callback: FilePickerCallback = (callback, value, meta) => {
  const input = document.createElement('input')
  input.setAttribute('type', 'file')
  input.setAttribute('accept', 'image/*')

  input.addEventListener('change', async (e: Event) => {
    let target = e.target as HTMLInputElement

    if (!target.files) return

    const file = target.files[0]

    let formData = new FormData()

    formData.append('pic', file)

    try {
      let response = await fetch('http://localhost:3000/api/upload', {
        method: 'POST',
        body: formData
      })

      let res = await response.json()

      callback(res.data[0].url)
    } catch (error) {
      console.log('报错了')
      console.log(error)
    }
  })

  input.click()
}

const initConfig = ref({
  apiKey: apiKey,
  plugins: 'lists link image table code help wordcount',
  language: 'zh_CN',
  file_picker_callback
})

watch(htmlContent, () => {
  emits('update:modelValue', htmlContent.value)
})

const onInit = (...args: any) => {
  emits('init', args[0], args[1] as EditorType)
}

onMounted(() => {
  if (location.hostname === '0.0.0.0') {
    console.error('本地不要使用 0.0.0.0 去启动，请改为localhost \n 否则会报： Resolved API key: invalid-origin')
  }
})
</script>
